import Taro from '@tarojs/taro'
import api from './api'

const loginByCode = (res) => {
  return new Promise((resolve, reject) => {
    // Taro.showLoading({
    //   title: '登录中',
    //   icon: 'none'
    // })
    Taro.removeStorage({
      key: 'token',
      success: function (res) {
        console.log(res)
      }
    })
    Taro.login().then(res => {
      console.log('===========')
      if (res.code) {
        console.log('===========')
        request(api.loginByCode, 'POST', {
          js_code: res.code
        }).then(res => {
          Taro.setStorage({
            key: 'loginInfo',
            data: res.info
          })
          Taro.setStorage({
            key: 'token',
            data: res.token
          })
          Taro.hideLoading()
          resolve()
        }).catch(() => {
          Taro.hideLoading()
          Taro.redirectTo({
            url: '/pages/login/login'
          })
        })
      }
    })
  })
}

const request = (url, method?, data?) => {
  return new Promise((resolve, reject) => {
    Taro.request<String>({
      url,
      method,
      data,
      header: {
        'Content-Type': 'application/json',
        token: Taro.getStorageSync('token')
      }
    }).then(res => res.data)
      .then(res => {
        if (typeof res !== 'object') {
          Taro.showToast({
            title: '网络错误',
            icon: 'none'
          })
          reject()
          return false
        }
        if (res.status === undefined) {
          if (res.code === 0 || res.code === 200) {
            resolve(res)
          } else if (res.code === 401) {
            loginByCode(res).then(_ => {
              reject(res)
            })
          } else {
            Taro.showToast({
              title: res.msg + res.code,
              icon: 'none'
            })
            reject(res)
          }
        } else if (res.status === 1) {
          resolve(res.data)
        } else {
          Taro.showToast({
            title: res.message || '网络错误',
            icon: 'none'
          })
          if (res.code === 3001 || res.code === 1011) {
            loginByCode(res)
          }
          reject(res)
        }
      }).catch(error => {
        Taro.showToast({
          title: '网络错误',
          icon: 'none'
        })
        reject(error)
      })
  })
}

export default request
